import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/editStudent")
public class EditStudentServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");


        try {
            Connection conn = JdbcUtil.getConnection();
            String sql = "SELECT * FROM classmates WHERE id = ?";
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, Integer.parseInt(id));
            ResultSet rs = pstmt.executeQuery();

            if (rs.next()) {
                Student student = new Student();
                student.setId(rs.getInt("id"));
                student.setName(rs.getString("name"));
                student.setNickn(rs.getString("nickn"));
                student.setAst(rs.getString("ast"));
                student.setCon(rs.getString("con"));
                student.setImp(rs.getString("imp"));

                req.setAttribute("student", student);
                req.getRequestDispatcher("/editStudent.jsp").forward(req, resp);
            } else {
                resp.sendRedirect(req.getContextPath() + "/stu");
            }
        } catch (SQLException e) {
            throw new ServletException("数据库操作失败", e);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        String name = req.getParameter("name");
        String nickn = req.getParameter("nickn");
        String ast = req.getParameter("ast");
        String con = req.getParameter("con");
        String imp = req.getParameter("imp");

        String sql = "UPDATE classmates SET name = ?, nickn = ?, ast = ?, con = ?, imp = ? WHERE id = ?";
        int result = JdbcUtil.executeUpdate(sql, name, nickn, ast, con, imp, Integer.parseInt(id));

        if (result > 0) {
            resp.sendRedirect(req.getContextPath() + "/stu");
        } else {
            req.setAttribute("msg", "更新同学信息失败");
            req.getRequestDispatcher("/editStudent.jsp").forward(req, resp);
        }
    }
}